<!-- 绑定支付宝、微信 -->
<template>
	<view>
		<cu-custom bgColor="" :isBack="true" class="brb_e">
			<block slot="content">{{paytype ==2 ? '支付宝' : '微信'}}</block>
			<!-- <block slot="content" v-if="paytype ==1">微信</block> -->
			<block slot="right" v-if="paytype==2">
				<!-- #ifndef MP-WEIXIN -->
				<view @tap="confir" class="text-black padding-lr">确定</view>
				<!-- #endif -->
				<!-- #ifdef MP-WEIXIN -->
				<view @tap="confir" class="text-black ">确定</view>
				<!-- #endif -->
			</block>
		</cu-custom>
		<!-- 中间表单 -->
		<view class="bind_box " v-if="paytype==2">
			<view class="cu-form-group brb_e" style="padding: 0;">
				<view class="title text-bold">姓名</view>
				<input class="text-df" type="text" v-model="content" placeholder-class="text-md text-gray" placeholder="请输入真实姓名，需与认证信息一致" />
			</view>
			<view class="padding-top padding-bottom brb_e flex align-center" style="" v-if="paytype == 2">
				<view class="title text-bold pr10">支付宝账号</view>
				<input class="text-df" type="text" v-model="account_id" placeholder-class="text-md text-gray" placeholder="请输入支付宝账号" />
			</view>

		</view>
		<view class="plr15 padding-top" v-if="paytype==1">
			<view class="  " style="padding: 0;">
				<view class="title text-bold w100">绑定的微信信息</view>
				<view class="flex align-center padding-top" v-if="wechatInfo">
					<text>{{wechatInfo.nickName}}</text>
					<image :src="wechatInfo.avatarUrl" mode="" class="img-100 round margin-left"></image>
				</view>
				<view class="padding-top" v-if="!wechatInfo">
					暂未绑定微信
				</view>
			</view>
			<view class="">
				<view class=" wx_btn text-center bg-theme text-white" @tap='getOpenid'>
					{{wechatInfo?'切换绑定的授权微信':'微信授权'}}</view>
				<!-- <view class=" wx_btn text-center  text-333" v-if="wechatInfo!=''" style="width: 600upx;">已进行微信授权,可以发起微信提现了哟 -->
			</view>
		</view>
	
		<uni-popup type="center" ref="tips">
			<form @submit="bindAccount" class="grace-form grace-margin-top" style="width: 80vw;">
				<view class="cu-list menu sm-border">
					<view class="flex align-center justify-between ptb10">
						<view class=" flex align-center" style="width: 100%;">
							<text class="text-lg flex_shrink padding-right-sm">
								<text class="text-red text-xl">*</text>
								<text>微信昵称：</text>
							</text>
							<input
								type="nickname"
								class="input"
								style="width: 100%;"
								v-model="wechatInfo.nickName"
								placeholder="请输入微信昵称"
								placeholder-style="font-size: 28rpx;"
								:placeholder-style="wechatInfo.nickName ? 'color:#666' : 'color:#BFBFBF'"
							/>
						</view>
					</view>
				</view>
				
				<view style="display: flex; justify-content: flex-start; align-items: center;">
					<text class="text-lg flex_shrink padding-right-sm">
						<text class="text-red text-xl">*</text>
						<text>微信头像：</text>
					</text>
					<button class='user-phone-btn' open-type="chooseAvatar" style="background-color: transparent; border: 1px solid #ccc; border-radius: 50%; width: 96upx; height: 96upx; text-align: center; display: inline-block;" @chooseavatar="onChooseAvatar">
					  <text v-if="!wechatInfo.avatarUrl">+</text>
					  <image v-if="wechatInfo.avatarUrl" :src="wechatInfo.avatarUrl" style="width: 96upx; height: 96upx;"></image>
					</button>
				</view>
		
				<view style="padding: 10upx 0;"><button class="btn_next round " style="width: 100%; margin: 0 auto; margin-top: 20upx;" form-type="submit">确认绑定</button></view>
			</form>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				content: '',
				imgList: '',
				imgList2: '',
				paytype: 2,
				account_id: '', //绑定的账号
				wechatInfo: '', //微信授权信息

			};
		},
		onLoad(e) {
			uni.showLoading({})
			this.paytype = e.type;
			this.getmsg()
			// if (e.type == 1) {
			// 	// 微信  获取微信openid
			// 	if (uni.getStorageSync('wechatInfo')) {
			// 		this.wechatInfo = uni.getStorageSync('wechatInfo')
			// 		console.log(this.wechatInfo, '==========this.wechatInfo ');
			// 		return
			// 	}
			// }
		},
		methods: {
			lookImg(url) { //图片预览
				this.$Common.lookImg(url);
			},
			getmsg() {
				this.$Request
					.get(this.$api.money.get_withdraw_account, {
						account_type: this.paytype
					})
					.then(res => {
						uni.hideLoading()
						console.log(res, '获取绑定数据');
						if (res.code == 1) {
							if (this.paytype == 2) {
								this.content = res.data.true_name
								this.account_id = res.data.account_id
								this.imgList = res.data.qrcode
								this.imgList2 = res.data.qrcode[0].aid
							} else {
								this.wechatInfo = {
									nickName: res.data.true_name,
									avatarUrl: res.data.qrcode
								}
							}

							// console.log(this.imgList2)
						} else {
							// this.$Common.toast(res.msg);
						}
					});
			},
			DelImg() {
				uni.showModal({
					content: '确定要删除这张照片吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							this.imgList = '';
							this.imgList2 = '';
							console.log(this.imgList);
						}
					}
				});
			},
			ChooseImage() {
				
				var _this = this
				// #ifdef APP-PLUS
				plus.android.requestPermissions(['android.permission.WRITE_EXTERNAL_STORAGE'], function(e) {
				
					var result = 0;
					for (var i = 0; i < e.granted.length; i++) {
						var grantedPermission = e.granted[i];
						console.log('已获取的权限：' + grantedPermission);
						result = 1
					}
					for (var i = 0; i < e.deniedPresent.length; i++) {
						var deniedPresentPermission = e.deniedPresent[i];
						console.log('拒绝本次申请的权限：' + deniedPresentPermission);
						result = 0
					}
					for (var i = 0; i < e.deniedAlways.length; i++) {
						var deniedAlwaysPermission = e.deniedAlways[i];
						console.log('永久拒绝申请的权限：' + deniedAlwaysPermission);
						result = -1
					}
					console.log(result);
					if(result === 1){
						uni.chooseImage({
							count: 1, //默认
							sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
							sourceType: ['album', 'camera'], //从相册选择
							success: res => {
								uni.showLoading();
								for (var i in res.tempFilePaths) {
									uni.uploadFile({
										url: _this.$Config('APIHOST') + _this.$api.common.upload,
										filePath: res.tempFilePaths[i],
										name: 'file[]',
										success: uploadFileRes => {
											uni.hideLoading();
											let imgs = JSON.parse(uploadFileRes.data);
											_this.imgList = imgs.data[0].path
											console.log(_this.imgList)
											_this.imgList2 = imgs.data[0].id
											// console.log('_this.imglist2', _this.imgList2);
										}
									});
								}
							}
						});
					}else if (result === 0){
						uni.showModal({
							title: '亲爱的用户',
							content: '您需要打开相册权限，才能使用完整功能。若您需要，请点击同意，重新授权',
							success(res) {
								if (res.confirm) {
									plus.android.requestPermissions(['android.permission.WRITE_EXTERNAL_STORAGE'])
								}
							}
						});
					}else{
						uni.showModal({
							title: '提示',
							content: '相册授权已被拒绝，请前往设置打开应用相册权限',
							showCancel: false,
							success: function (res) {
								if (res.confirm) {
									var main = plus.android.runtimeMainActivity();  
									var Intent = plus.android.importClass("android.content.Intent");
									var mIntent = new Intent('android.settings.WIRELESS_SETTINGS');  
									main.startActivity(mIntent); 
								}
							}
						});
					}
				}, function(e) {
					console.log('Request Permissions error:' + JSON.stringify(e));
				});
				// #endif
				// #ifdef MP
				uni.chooseImage({
					count: 1, //默认
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: res => {
						uni.showLoading();
						for (var i in res.tempFilePaths) {
							uni.uploadFile({
								url: _this.$Config('APIHOST') + _this.$api.common.upload,
								filePath: res.tempFilePaths[i],
								name: 'file[]',
								success: uploadFileRes => {
									uni.hideLoading();
									let imgs = JSON.parse(uploadFileRes.data);
									_this.imgList = imgs.data[0].path
									console.log(_this.imgList)
									_this.imgList2 = imgs.data[0].id
									// console.log('_this.imglist2', _this.imgList2);
								}
							});
						}
					}
				});
				// #endif
			
			},
			getOpenid() {
				// 2022.11.9微信改了规则
				this.$refs.tips.open();
				return;
				uni.login({
					success: (res) => {
						let code = res.code;
						uni.getUserProfile({
							provider: 'weixin',
							success: infoRes => {
								console.log(res, infoRes, '=========');
								this.wechatInfo = infoRes.userInfo;
								console.error(this.paytype);
								if (this.paytype == 1) {
									this.decryptUser(code, infoRes, () => {
										// this.bindAccount(infoRes);
									});
								} else {
									this.bindAccount(infoRes);
								}
								
							},
						})
					}
				})
			},
			confir() {
				//点击确定
				if (this.paytype == 2) {
					if (!this.content) {
						this.$Common.toast('请输入姓名')
						return
					}
					// if (this.imgList == '') {
					// 	console.log(this.imgList);
					// 	this.$Common.toast('请上传收款二维码')
					// 	return
					// }
				}
				if (this.paytype == 2) {
					if (!this.account_id) {
						this.$Common.toast('请填写支付宝账号')
						return
					}
				}
				this.$Request
					.post(this.$api.money.bind_withdraw_account, {
						true_name: this.content || '',
						qrcode: this.imgList || '',
						account_type: this.paytype, //账户类型 1 微信 2 支付宝 3 银行卡
						is_default: 0,
						account_id: this.account_id || this.uniopenid || '', //支付宝账号  微信openid
					})
					.then(res => {
						// console.log(this.imgList,'图片');
						if (res.code == 1) {
							this.$Common.toast(res.msg);
							setTimeout(() => {
								uni.navigateBack({});
							}, 1000)

						} else {
							this.$Common.toast(res.msg);
						}
					});
			},
			decryptUser(code, infoRes, callback) {
				let that = this;
				that.$Request.post(that.$api.wechat.wx_login, {
						encryptedData: encodeURIComponent(infoRes.encryptedData),
						iv: encodeURIComponent(infoRes.iv),
						code: code,
						signature: infoRes.signature,
						rawData:infoRes.rawData,
						avatar:infoRes.userInfo.avatarUrl,
						nickname:infoRes.userInfo.nickName
					})
					.then(result => {
						// console.log('后台返回登录信息', result.code);
						if (result.code == 1) {
							console.log(result.data,result.data.result,'result.result');
							// 如果后台返回来的是 result 字段,表示此账号还没有绑定过手机号 跳转到绑定手机号页面
							// 如果后台返回的是 userinfo 字段,表示已经登录成功,把用户信息存到 store 中,并返回跳转来的页面
							if (result.data.result) {
								console.log('后台返回的result',result.data.result);
								that.rawData = result.data.result;
								that.$Common.toast('授权成功，请点击按钮进行手机号授权');
							} else if (result.data.userinfo) {
								console.log(result.data.userinfo,'已绑定手机号');
								that.wechatInfo = result.data.userinfo;
								that.wechatInfo.nickName = result.data.userinfo.user_nickname;
								that.wechatInfo.avatarUrl = result.data.userinfo.head_img;
								let info = that.userinfo = result.data.userinfo;
								//uni.$emit('appLoginSuccess', {});
								//uni.$emit('wechatLogin', {}); //监听微信登录
								uni.setStorageSync('USERINFO', info);
								uni.setStorageSync('userToken', info.user_token);
								uni.removeStorageSync('PageCur');
								uni.removeStorageSync('chooseCity');
								console.error(that.wechatInfo);
								if (typeof callback === 'function') callback();
							}
						} else if (result.code == -999) {
							// 服务器解析参数错误
							that.$Common.toast(result.msg);
						} else {
							that.$Common.toast('授权失败，请使用其他方式登录');
						}
					})
					.catch(err => {
						console.log('ERROR_catch', err);
						that.$Common.toast(err.msg);
					});
			},
			onChooseAvatar(e) {
				console.error(e);
				this.$set(this.wechatInfo, "avatarUrl", e.detail.avatarUrl);
				if (e.detail.avatarUrl) {
					uni.uploadFile({
						url: this.$Config('APIHOST') + this.$api.common.upload,
						filePath: e.detail.avatarUrl,
						name: 'file',
						success: uploadFileRes => {
							uni.hideLoading();
							// console.error(uploadFileRes);
							let data = JSON.parse(uploadFileRes.data);
							console.error(data);
							if (data.code == 1) {
								this.$set(this.wechatInfo, "avatarUrl", data.data[0].path);
							}
						}
					});
				}
			},
			bindAccount(infoRes) {
				let user = null;
				this.$set(this.wechatInfo, 'account_id', '');
				// console.error(uni.getStorageSync('USERINFO'));
				if (user = uni.getStorageSync('USERINFO')) {
					// user = JSON.parse(user);
					// console.error(user);
					this.$set(this.wechatInfo, 'account_id', user.oid);
					this.$set(this.wechatInfo, 'openId', user.oid);
				}
				// console.error(user);
				// console.error(this.paytype);
				if (!this.wechatInfo.nickName) {
					return this.$Common.toast('微信昵称不可为空');
				}
				let port = uni.getSystemInfoSync().platform;
				// console.log(port);
				this.$Request
					.post(this.$api.money.bind_withdraw_account, {
						true_name: this.wechatInfo.nickName,
						qrcode: this.wechatInfo.avatarUrl || '',
						account_type: this.paytype, //账户类型 1 微信 2 支付宝 3 银行卡
						is_default: 0,
						account_id: this.paytype == 2 ? this.account_id : this.wechatInfo.openId, //支付宝账号  微信openid
						src: port == 'android' || port == 'ios' ? 'app' : 'mini'
					})
					.then(res => {
						// console.log(this.imgList,'图片');
						if (res.code == 1) {
							this.$Common.toast(res.msg);
							setTimeout(() => {
								uni.navigateBack({});
							}, 1000)
				
						} else {
							this.$Common.toast(res.msg);
						}
					});
			}
		}
	};
</script>

<style lang="scss" scoped>
	page {
		height: 100%;
		background: #ffffff;
	}

	.bind_box {
		background: #fff;
		width: 686rpx;
		height: 791rpx;
		margin: 30rpx auto;
		border-radius: 30rpx;
		overflow: hidden;
	}

	.erweima_box {
		position: relative;
		text-align: center;

		.kuang {
			width: 150rpx;
			height: 150rpx;
		}

		.erweima {
			padding: 0;
		}

		.erweima_img {
			width: 150rpx;
			height: 150rpx;
		}
	}

	.solids::after {
		content: '';
		border: 0;
	}

	.wx_btn {
		width: 300upx;
		height: 88upx;
		line-height: 88upx;
		margin: 200upx auto 0;
		border-radius: 999upx;

	}
	
	.user-phone-btn {
	  margin: 0rpx;
	  padding: 0rpx;
	}
	
	button::after{
	  border: none;
	}
</style>
